import os,tempfile,shutil,commands
import pickle
import sys
import time
from crvclient import doSetUntilDone

inf=open(sys.argv[1],"r")

vmid=pickle.load(inf)
serverstr=pickle.load(inf)
serverhostname=pickle.load(inf)

MetaDataProvided=False

while not MetaDataProvided:

    cmdstr="curl -s \"%s/getVMAttr?vmid=%s&name=MetaDataProvided\""%(serverstr,vmid)

    (status,output)=commands.getstatusoutput(cmdstr)

    print "Running command=%s, status=%d, output=%s"%(cmdstr,status,output)
    if output=="True":
        MetaDataProvided=True

    time.sleep(5)
    
#now obtain metadata
cmdstr="curl -s \"%s/getVMAttr?vmid=%s&name=MetaData\""%(serverstr,vmid)
(status,output)=commands.getstatusoutput(cmdstr)
print "Running command=%s, status=%d, output=%s"%(cmdstr,status,output)

#Metadata will be the result from "tar cz certfiles|base64 -w 0"
#save it somewhere


metadata=output

base64file=tempfile.gettempdir()+"metadata.tgz.base64"

ouf=open(base64file,"w")
ouf.write(metadata)
ouf.close()

try:
    os.makedirs("/etc/puppet")
except:
    pass

cmdstr="base64 -d -w 0 %s|tar zx -C /etc/puppet/"%(base64file)
(status,output)=commands.getstatusoutput(cmdstr)
print "Running command=%s, status=%d, output=%s"%(cmdstr,status,output)

cmdstr='/etc/init.d/rsyslog start'
(status,output)=commands.getstatusoutput(cmdstr)
print "Running command=%s, status=%d, output=%s"%(cmdstr,status,output)

#Triggering policy:
#1. Triggered when new role is to be applied
#2. If one role failed the apply-run, (grep for "err:" in puppet output), trigger the application of the role it depends on (trigger provider).
#3. If one role succeeded in the apply-run, trigger all its non-local dependent (trigger receivers)

#Infinite loop which will take care of running puppet
#while True:

    #wget getVMAttr("needrun")
    #if need to run
    #   wget setVMAttr("needrun","False")
    #    get from server what roles are being applied to this VM
    #    activeroles=[xx,x,x,x,x]
    
    #    run puppet once

    #    if puppet run success
    #        set all activeroles success
    #    else
    #        set all activeroles fail
    #sleep for a while
#    time.sleep(1)

oufname="/var/log/crvclient.puppet.log"

while True:

    ouf=open(oufname,"a")
    starttime=time.time()
    cmdstr='puppetd --configtimeout=10 --test --debug --server=%s' % serverhostname
    (status,output)=commands.getstatusoutput(cmdstr)
    endtime=time.time()

    ouf.write("Command=%s, status=%d, output=%s\n"%(cmdstr,status,output))
    ouf.write("Start time=%f, end time=%f\n"%(starttime,endtime))

    ouf.close()
    
    time.sleep(30)
    
#cmdstr='/etc/init.d/puppet restart'
#(status,output)=commands.getstatusoutput(cmdstr)
#print "Running command=%s, status=%d, output=%s"%(cmdstr,status,output)
